package com.util;

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class HttpRequest {

	public static String doPost(String url ,String jsonObj) throws ClientProtocolException, IOException{
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost  post = new HttpPost(url);
        post.setEntity(new StringEntity(jsonObj,"utf-8"));
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
//        System.out.println(response.getStatusLine().getStatusCode());
        if (entity != null) {
        	if(response.getStatusLine().getStatusCode()==200){
        		return EntityUtils.toString(entity,"utf-8");
        	}else{
        		return null;
        	}
            
        } else{
            return null;
        }
    }
	    
	    public static String  doGet(String url) throws ClientProtocolException, IOException{
	        HttpClient client = HttpClientBuilder.create().build();
	        HttpGet get = new HttpGet(url);
	        HttpResponse response = client.execute(get);
	        HttpEntity entity = response.getEntity();  
	        if (entity != null) {  
	            return EntityUtils.toString(entity,"utf-8");
	        } else{
	            return null;
	        }
	        
	    }
	    
	    public static String doDelete(String url) throws ClientProtocolException, IOException{
	        HttpClient client = HttpClientBuilder.create().build();
	        HttpDelete del = new HttpDelete(url);
	        HttpResponse response = client.execute(del);
	        HttpEntity entity = response.getEntity();  
	        if (entity != null) {  
	            return EntityUtils.toString(entity,"utf-8");
	        } else{
	            return null;
	        }
	    }
	    
	    public static String doPut(String url , String jsonObj) throws ClientProtocolException, IOException{
	        HttpClient client = HttpClientBuilder.create().build();
	        HttpPut  put = new HttpPut(url);
	        put.setEntity(new StringEntity(jsonObj,"utf-8"));
	        HttpResponse response = client.execute(put);
	        HttpEntity entity = response.getEntity();  
	        if (entity != null) {  
	            return EntityUtils.toString(entity,"utf-8");
	        } else{
	            return null;
	        }
	    }
	    
	    public static void main(String[] args) throws ClientProtocolException, IOException {
	    	System.out.println(HttpRequest.doPost("https://www.baidu.com/",""));
	    }

}

